import { defineStore } from "pinia";
import { resetRouter } from "@/routes/routes_index";
import { TypeUserInfoI, TypeUserQueryI } from "@/api/user/user_types";
import { useStorage } from "@vueuse/core";
import { ref } from "vue";
import { pinia } from "../storeIndex";
import * as authApi from "@/api/auth/auth_api_index";
import * as userApi from "@/api/user/user_api_index";
import {
    TypeLoginDataI,
    TypeLoginResultI,
    TypeCaptchaResultI,
} from "@/api/auth/auth_types";

export const useUserStore = defineStore("user", () => {
    const user: TypeUserInfoI = {
        roles: [],
        perms: [],
    };

    const token = useStorage("accessToken", "");

    const testString = "testString";

    // remove token
    // todo: 为啥都要返回promise对象
    function resetToken() {
        console.log("in resetToken");
        return new Promise<void>((resolve) => {
            token.value = "";
            // resetRouter();
            resolve();
        });
    }

    /**
     * 登录
     *
     * @param {LoginData}
     * @returns
     */
    function login(loginData: TypeLoginDataI) {
        return new Promise<void>((resolve, reject) => {
            authApi.loginApi(loginData)
                .then((response) => {
                    const { tokenType, accessToken } = response.data;
                    token.value = tokenType + " " + accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
                    resolve();
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }
    // user logout
    function logout() {
        return new Promise<void>((resolve, reject) => {
            authApi.logoutApi()
                .then(() => {
                    token.value = "";
                    location.reload(); // 清空路由
                    resolve();
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    //为什么采用 返回 promise
// 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<TypeUserInfoI>((resolve, reject) => {
        userApi.getUserInfoApi()
        .then(({ data }) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          if (!data.roles || data.roles.length <= 0) {
            reject("getUserInfo: roles must be a non-null array!");
            return;
          }
          Object.assign(user, { ...data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

//   getUserInfo().then(()=>{
//     //确保 getUserInofo已经完成后，再运行以下代码
//     //lots of code
//   })


    const queryParamsIntial: TypeUserQueryI = {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        keywords: undefined,
        startTime: undefined,
        endTime: undefined,
    };

    const queryParamsRef = ref<TypeUserQueryI>({
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        keywords: undefined,
        startTime: undefined,
        endTime: undefined,
    });

    function resetQueryParams(): void {
        queryParamsRef.value = {
            pageNum: 1,
            pageSize: 10,
            deptId: undefined,
            keywords: undefined,
            startTime: undefined,
            endTime: undefined,
        };
        //Object.assign(queryParams, queryParamsIntial)
        console.log("resetQueryParams queryParams", queryParamsRef.value);
    }
    return {
        token,
        user,
        queryParamsRef,
        // testString,
        login,
        getUserInfo,
        logout,
        resetToken,
        resetQueryParams,
    };
});
// 非setup
export function useUserStoreHook() {
    return useUserStore(pinia);
}
